import re

from django.contrib.auth.models import User
from  django_redis import  get_redis_connection
from rest_framework.serializers import ModelSerializer
from rest_framework_simplejwt.serializers import TokenObtainSlidingSerializer
from rest_framework import  serializers
from config.dbs.redisconfig import LOGIN_VERIFY_CODE_TEMPLATE
from user.models import *

class UserDetailSerializer(ModelSerializer):
    class Meta:
        model = UserDetail
        fields ='__all__'

        extra_kwarg ={
            'user':{'write_only':True},
            'avatar':{'write_only':True}, #单独写接口去实现头像操作
        }

class UserSerializer(ModelSerializer):
    userdetail = UserDetailSerializer(required=False,read_only=True)

    class Meta:
        model= User
        exclude =['password','last_name','user_permissions',]

        extra_kwargs = {
            'last_login':{'read_only':True},
            'is_superuser':{'read_only':True},
            'is_staff':{'read_only':True},
            'is_active':{'read_only':True},
            'date_joined':{'read_only':True},
            'groups':{'read_only':True},
        }

class MyTokenSerializer(TokenObtainSlidingSerializer):
    def validate(self, attrs):
        data = super().validate(attrs)
        data['id'] = self.user.id
        data['username'] = self.user.username
        data['avatar'] =self.user.userdetail.avatar if hasattr(self.user,'userdetail') else None

        # 图形验证码的校验
        # 1、拿到传入的验证码
        uuid =self.initial_data.get('uuid')
        verify =self.initial_data.get('verify')

        if not uuid or not verify:
            return {'msg':'请输入验证码'}

        #2、获取缓存的code
        cache = get_redis_connection(alias='verify_codes')
        redis_verify =cache.get(LOGIN_VERIFY_CODE_TEMPLATE % uuid)
        cache.delete(LOGIN_VERIFY_CODE_TEMPLATE % uuid) # 急时释放Redis空间


        if not redis_verify:
            return {'msg':'验证码过期'}

        # 3、比较两个码
        if redis_verify.lower() !=verify.lower():
            return {'msg':'验证码错误'}
        return data

class CreateUserSerializer(ModelSerializer):
    class Meta:
        model=User
        fields = ['username','first_name','email']

        extra_kwargs={
            'first_name':{
                'required':True,
            },
            'email':{
                'required':True,
            },
        }


class UpdatePasswordSerializer(ModelSerializer):
    password =serializers.CharField(max_length=60,label='旧密码')
    new_password =serializers.CharField(max_length=60,label='新密码')
    repeat_password =serializers.CharField(max_length=60,label='确认密码')

    def validate(self, attrs):
        if attrs['new_password'] != ['repeat_password']:
            raise serializers.ValidationError('两次输入的密码不一致')
        return attrs

class AreaSerializer(ModelSerializer): # 省行政区查询
    class Meta:
        model = Area
        fields = ['id','name']

class ParentSerializer(ModelSerializer): # 省内城市查询
    '''
    可以拿到id，name同时拿到这一级下属行政级别的全部(省的id，name和省内所有全部城市)
    '''
    area_set = AreaSerializer(many=True,read_only=True)

    class Meta:
        model = Area
        fields = ['id', 'name','area_set']

class AddressSerializer(ModelSerializer):
    province_name = serializers.CharField(source='province.name',read_only=True)
    city_name = serializers.CharField(source='city.name',read_only=True)
    district_name = serializers.CharField(source='district.name',read_only=True)
    class Meta:
        model = Address
        exclude =['is_delete']

    def validate_phone(self,value):
        if not re.match(r'1[3-9]\d{9}',value):
            raise serializers.ValidationError('手机号码格式错误')
        return value